# _*_ coding:utf-8 _*_
"""
__Author__    :  Icy ldw
__Date__      :  2019/2/23
__File__      :  logistic_.py
__Desc__      :
"""
import random

import numpy as np
from sklearn.datasets import load_breast_cancer
from matplotlib import pyplot as plt


def getDataSet():
    barestCancer = load_breast_cancer()
    # print(dir(barestCancer))
    data = barestCancer['data']
    target = barestCancer['target']
    feature_names = barestCancer['feature_names']
    # print(data[:10,:3])
    return data[:, :2], target


def sigmoid(z):  # 应该是预测函数
    return 1 / (1 + np.exp(-z))


def gradAscent(dataMatIn, classLabel, maxCycles=500):
    dataMatrix = np.mat(dataMatIn)
    labelMat = np.mat(classLabel).transpose()  # 转为列向量
    m, n = np.shape(dataMatrix)
    learn_rate = 0.1
    # REW:权重的shape设置很重要
    weights = np.ones((n, 1))  # 对应特征维数
    for i in range(maxCycles):
        h = sigmoid(dataMatrix * weights)
        error = (labelMat - h)  # 梯度上升法
        weights += learn_rate * dataMatrix.T * error
    return weights


def stocGradAscent0(dataMat, labelMat):  # 随机梯度上升，当数据量比较大时，每次迭代都选择全量数据进行计算，计算量会非常大。所以采用每次迭代中一次只选择其中的一行数据进行更新权重。
    dataMatrix = np.mat(dataMat)
    classLabels = labelMat
    m, n = np.shape(dataMatrix)
    alpha = 0.01  # 学习率
    maxCycles = 500
    # REW:权重的shape设置很重要
    weights = np.ones((n, 1))
    for k in range(maxCycles):
        for i in range(m):  # 遍历每一行
            h = sigmoid(sum(dataMatrix[i] * weights))
            error = classLabels[i] - h
            weights = weights + alpha * error * dataMatrix[i].transpose()  # 样本转置为了对应权重是列向量
    return weights


def stocGradAscent1(dataMat, labelMat,maxCycles=150):  # 改进版随机梯度上升，在每次迭代中随机选择样本来更新权重，并且随迭代次数增加，权重变化越小。
    dataMatrix = dataMat
    classLabels = labelMat
    m, n = np.shape(dataMatrix)
    weights = np.ones(n)  # REW:权重的shape设置很重要(对应n个特征设置权重数量)
    for j in range(maxCycles):
        dataIndex = [i for i in range(m)]
        for i in range(m):
            alpha = 4 / (1 + j + i) + 0.0001  # 随迭代次数增加，权重变化越小
            randIndex = int(random.uniform(0, len(dataIndex)))  # 随机抽样
            h = sigmoid(sum(dataMatrix[randIndex] * weights))
            error = classLabels[randIndex] - h
            dw = alpha * error * dataMatrix[randIndex].transpose()
            weights = weights + dw
            del dataIndex[randIndex]  # 去除已经抽取的样本
    return weights


def plotBestFit(weights):
    data, label = getDataSet()
    dataMatrix = np.mat(data)
    labelMat = np.mat(label).transpose()
    m, n = np.shape(dataMatrix)
    xcord1 = [];
    ycord1 = []
    xcord2 = [];
    ycord2 = []
    # 两个类别分别添加x轴，y轴的数据
    for i in range(m):
        if int(labelMat[i]) == 1:
            xcord1.append(dataMatrix[i, 0])
            ycord1.append(dataMatrix[i, 1])
        else:
            xcord2.append(dataMatrix[i, 0])
            ycord2.append(dataMatrix[i, 1])
    fig: plt.Figure = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(xcord1, ycord1, s=30, c='r')
    ax.scatter(xcord2, ycord2, s=30, c='green')
    x = np.arange(1, 30, 0.1)
    y = weights[0] * x / (-weights[1])
    print(x[:10], y[:10])
    ax.plot(x, y)
    plt.xlabel('X1')
    plt.ylabel('X2')
    plt.show()


def train():
    data, labels = getDataSet()
    weights = gradAscent(data, labels)
    plotBestFit(weights)


"""
从疝气病症预测病马的死亡率
这里的数据集是经过预处理的：
缺失值选择实数0填充，
对于测试数据集，类别标签缺失的数据，丢掉
"""


def classifyVector(inX, weights):
    prob = sigmoid(sum(inX * weights))
    if prob > 0.5:
        return 1.0
    else:
        return 0.0


def colicTest():
    frTrain = open(r'F:\Resources\Dataset\horseColicTraining.txt')
    frTest = open(r'F:\Resources\Dataset\horseColicTest.txt')
    trainingSet = [];
    trainingLabels = []
    for line in frTrain.readlines():
        currLine = line.strip().split('\t')
        lineArr = []
        for i in range(21):
            lineArr.append(float(currLine[i]))
        trainingSet.append(lineArr)
        trainingLabels.append(float(currLine[21]))
    trainWeights = stocGradAscent1(np.array(trainingSet),trainingLabels,500)
    errorCount = 0;numTestVec=0.0
    for line in frTest.readlines():
        numTestVec += 1.0
        currLine = line.strip().split('\t')
        lineArr = []
        for i in range(21):
            lineArr.append(float(currLine[i]))
        if int(classifyVector(np.array(lineArr),trainWeights)) != int(currLine[21]):
            errorCount += 1
        errorRate = (float(errorCount) / numTestVec)
        print("the error rate of this test is: %f" % errorRate)
        return errorRate
def multiTest():
    numTests = 10; errorSum=0.0
    for k in range(numTests):
        errorSum += colicTest()
    print("after %d iterations the average error rate is: %f" % (numTests, errorSum / float(numTests)))


if __name__ == "__main__":
    multiTest()
